<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of FormData
 *
 * @author thuan_000
 */
abstract class FormData extends CFormModel {

    const PRICE_PREFIX = "PRICE_";
    const DANH_SACH_NHA_THAU_THAM_GIA_DAU_THAU = 1;
    const THONG_TIN_KHAC = 2;
    const KET_QUA_DAU_THAU = 3;
    const KE_HOACH_DAU_THAU = 4;
    const THONG_BAO_MOI_THAU = 5;
    const PAYMENT_DONE = 1;
    const PAYMENT_APART = 2;
    const PAYMENT_NO = 3;
    const CHECKED = 1;
    const NOT_CHECKED = 2;
    const PENDING_CHECKED = 0;

    private function getPrimaryAttribute() {
        return array(
            'id',
            'name',
            'type',
            'user_create',
            'created_at',
            'user_update',
            'updated_at',
            'price',
            'status',
            'is_checked',
            'checked_at',
            'user_check',
            'cause',
            'paid',
            'remain',
            'image_url',
        );
    }

    public $id;
    public $name;
    public $type;
    public $user_create;
    public $created_at;
    public $user_update;
    public $updated_at;
    public $price;
    public $status;
    public $is_checked;
    public $checked_at;
    public $user_check;
    public $cause;
    public $paid;
    public $remain;
    public $image_url;

    /**
     * @return array list attribute
     */
    abstract public function attributeType();

    abstract public function searchAttribute();

    public function save() {
        $form = NULL;
        $is_new = FALSE;
        if ($this->id) {
            $form = Form::model()->findByPk($this->id);
            if (!$form)
                return;
        }else {
            $form = new Form();
            $is_new = TRUE;
        }
        foreach ($this->getPrimaryAttribute() as $prop) {
            $form->$prop = $this->$prop;
        }
        if ($is_new) {
            $form->price = (float) FormData::getFormPrice($form->type);
            $form->remain = (float) FormData::getFormPrice($form->type);
        }
        $rs = $form->save();
        if ($rs) {
            $this->id = $form->id;
            foreach ($this->attributeType() as $name => $type) {
                $this->saveAttribute($name, $type);
            }
            return true;
        }
    }

    protected function saveAttribute($name, $type = 'varchar') {
        $form_meta = NULL;
        if ($this->id) {
            $form_meta = FormMeta::model()->find('form_id = :form_id and attribute = :attribute', array(':form_id' => $this->id, ':attribute' => $name));
            switch ($type) {
                case FormMeta::TYPE_TEXT:
                    $this->saveTextAttribute($name, $form_meta);
                    break;
                case FormMeta::TYPE_VARCHAR:
                    $this->saveVarcharAttribute($name, $form_meta);
                    break;
                default:
                    break;
            }
        }
    }

    private function saveTextAttribute($name, $form_meta) {
        $att_value = null;
        if ($form_meta) {
            $att_id = $form_meta->attribute_value;
            $att_value = AttributeValue::model()->findByPk($att_id);
            if (!$att_value) {
                $att_value = new AttributeValue();
            }
            $form_meta->attribute_type = FormMeta::TYPE_TEXT;
        } else {
            $form_meta = new FormMeta();
            $form_meta->attribute_type = FormMeta::TYPE_TEXT;
            $att_value = new AttributeValue();
        }
        $att_value->value = $this->$name;
        $form_meta->form_id = $this->id;
        $form_meta->attribute = $name;
        if ($att_value->save()) {
            $form_meta->attribute_value = $att_value->id;
            $form_meta->save();
        }
    }

    private function saveVarcharAttribute($name, $form_meta) {
        if (!$form_meta) {
            $form_meta = new FormMeta();
        }
        $form_meta->attribute_type = FormMeta::TYPE_VARCHAR;
        $form_meta->form_id = $this->id;
        $form_meta->attribute = $name;
        $form_meta->attribute_value = $this->$name;
        $form_meta->save();
    }

    public function loadById($id) {
        $form = Form::model()->findByPk($id);
        if (!$form) {
            return FALSE;
        }
        foreach ($this->getPrimaryAttribute() as $name) {
            $this->$name = $form->$name;
        }
        foreach ($form->formMetas as $form_meta) {
            $name = $form_meta->attribute;
            switch ($form_meta->attribute_type) {
                case FormMeta::TYPE_VARCHAR:
                    $this->$name = $form_meta->attribute_value;
                    break;
                case FormMeta::TYPE_TEXT:
                    if ($form_meta->attribute_value) {
                        $att_text = AttributeValue::model()->findByPk($form_meta->attribute_value);
                        if ($att_text) {
                            $this->$name = $att_text->value;
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    public function search() {
        $connection = Yii::app()->db;
        $key = "id";
        $sql = $this->searchSql();
        $rowcountsql = $this->searchCountSql();
        $command = $connection->createCommand($rowcountsql);
        $count = $command->queryScalar(); // provide count for pagination
// create data provider that works with CGridView
        $dataProvider = new CSqlDataProvider($sql, array(
            'keyField' => $key,
            'totalItemCount' => $count,
            'pagination' => array(
                'pageSize' => 5,
            ),
        ));
        return $dataProvider;
    }

    protected function searchSql() {
        $select = ' SELECT f.*';
        $from = ' FROM tbl_form f';
        $where = " Where f.type = {$this->type} ";
        if ($this->id && trim($this->id) != '') {
            $where .= " and f.id = {$this->id} ";
        }
        foreach ($this->searchAttribute() as $key => $value) {
            $select .= ", fm{$key}.attribute_value as {$value} ";
            $from .= " left join tbl_form_meta fm{$key} ON fm{$key}.`form_id` = f.`id` ";
            $where .= " and fm{$key}.`attribute` = '{$value}'";
            if ($this->$value && trim($this->$value) != '') {
                $where .= " and fm{$key}.`attribute_value` like '%{$this->$value}%'";
            }
        }
        return $select . $from . $where;
    }

    protected function searchCountSql() {
        $select = ' SELECT count(f.id)';
        $from = ' FROM tbl_form f';
        $where = " Where f.type = {$this->type} ";
        foreach ($this->searchAttribute() as $key => $value) {
            $from .= " left join tbl_form_meta fm{$key} ON fm{$key}.`form_id` = f.`id` ";
            $where .= " and fm{$key}.`attribute` = '{$value}'";
            if ($this->$value && trim($this->$value) != '') {
                $where .= " and fm{$key}.`attribute_value` like '%{$this->$value}%'";
            }
        }
        return $select . $from . $where;
    }

    protected function sqlGetAllByPayment($mode) {
        $select = ' SELECT f.*';
        $from = ' FROM tbl_form f';
        $where = "";
        switch ($mode) {
            case FormData::PAYMENT_DONE:
                $where = " Where f.remain = f.price ";
                break;
            case FormData::PAYMENT_APART:
                $where = " Where f.remain > 0 and  Where f.remain < f.price";
                break;
            case FormData::PAYMENT_NO:
                $where = " Where f.remain > 0 and  Where f.paid = 0";
                break;

            default:
                break;
        }
        return $select . $from . $where;
    }

    protected function sqlCountAllByPayment($mode) {
        $select = ' SELECT count(f.id)';
        $from = ' FROM tbl_form f';
        $where = "";
        switch ($mode) {
            case FormData::PAYMENT_DONE:
                $where = " Where f.remain = f.price ";
                break;
            case FormData::PAYMENT_APART:
                $where = " Where f.remain > 0 and  Where f.remain < f.price";
                break;
            case FormData::PAYMENT_NO:
                $where = " Where f.remain > 0 and  Where f.paid = 0";
                break;

            default:
                break;
        }
        return $select . $from . $where;
    }

    public function getAllByPayment($mode) {
        $connection = Yii::app()->db;
        $key = "id";
        $sql = $this->sqlGetAllByPayment($mode);
        $rowcountsql = $this->sqlCountAllByPayment($mode);
        $command = $connection->createCommand($rowcountsql);
        $count = $command->queryScalar(); // provide count for pagination
// create data provider that works with CGridView
        $dataProvider = new CSqlDataProvider($sql, array(
            'keyField' => $key,
            'totalItemCount' => $count,
            'pagination' => array(
                'pageSize' => 5,
            ),
        ));
        return $dataProvider;
    }

    public static function getFormPrice($type) {
        $path = FormData::PRICE_PREFIX . $type;
        return ConfigData::getConfig($path);
    }

    public static function setFormPrice($type, $price) {
        $path = FormData::PRICE_PREFIX . $type;
        return ConfigData::setConfig($path, $price);
    }

    public static function getFormByPricePath($path) {
        $type = str_replace(FormData::PRICE_PREFIX, '', $path);
        switch ($type) {
            case FormData::THONG_BAO_MOI_THAU:
                return 'Thông báo mời thầu';
                break;

            case FormData::KE_HOACH_DAU_THAU:
                return 'Kế hoạch đấu thầu';
                break;
            default:
                break;
        }
    }

    public function getPayment() {
        if ($this->remain == 0) {
            $value = 'Đã thanh toán đủ';
        } else {
            if ($this->remain == $this->price) {
                $value = 'Chưa thanh toán';
            } else {
                $value = 'Đã thanh toán ' . $this->paid . ', còn lại ' . $this->remain;
            }
        }
        return $value;
    }

    public static function getPaymentState($remain, $price) {
        if ($remain == 0) {
            $value = 'Đã thanh toán đủ';
        } else {
            if ($remain == $price) {
                $value = 'Chưa thanh toán';
            } else {
                $value = 'Đã thanh toán một phần';
            }
        }
        return $value;
    }

    public function getChecked() {
        switch ($this->is_checked) {
            case '1':
                $value = 'Đã duyệt';
                break;
            case '2':
                $value = 'Không được duyệt (Lý do : ' . $this->cause . ')';
                break;
            case '0':
                $value = 'Chờ duyệt';
                break;
            default :
                $value = 'Chờ duyệt';
                break;
        }
        return $value;
    }

}
